package 生产者消费者;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author dexi.che on 2021/7/25  2:54 下午
 */
public class SolutionLock {
    public static Lock lock = new ReentrantLock();
    public static Condition full = lock.newCondition();
    public static Condition empty = lock.newCondition();
    public static Integer FULL = 5;
    public static volatile Integer count = 0;

    static class Producer implements Runnable {
        @Override
        public void run() {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            for (int i = 0; i < 5; i++) {
                try {
                    lock.lock();
                    while (count == FULL) {
                        full.await();
                    }
                    count++;
                    System.out.println(Thread.currentThread().getName() + ": producer:" + count);
                    empty.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }
    }

    static class Consumer implements Runnable {
        @Override
        public void run() {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            for (int i = 0; i < 5; i++) {
                try {
                    lock.lock();
                    while (count == 0) {
                        empty.await();
                    }
                    count--;
                    System.out.println(Thread.currentThread().getName() + ": consumer:" + count);
                    full.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }
    }

    public static void main(String[] args) {
        new Thread(new SolutionOne.Producer()).start();
        new Thread(new SolutionOne.Consumer()).start();
    }
}
